<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Applybuy extends CI_Controller
{

    /**
     * 采购申请
     *
     * Maps to the following URL
     *        http://example.com/index.php/welcome
     *    - or -
     *        http://example.com/index.php/welcome/index
     *    - or -
     * Since this controller is set as the default controller in
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see https://codeigniter.com/user_guide/general/urls.html
     */
    function __construct()
    {
        parent::__construct();
        $this->load->model('Function_m','fun');
        $this->pageSize =$this->config->item('pagenum');
    }
    //采购申请列表
    public function applyList() {
        //获取所有工厂列表
        $factorys = $this->fun->getdatabaseslist("db_factory");
        $this->tpl->assign("factorys",$factorys);
        //获取所有供应商列表
        $suppliers = $this->fun->getdatabaseslist("d_factorysupplier");
        $this->tpl->assign("suppliers",$suppliers);
        //拼接搜索条件
        $nowpage = $_REQUEST["pageid"];
        if ($nowpage == "") $nowpage = 1;
        $where = "";
        //拼接搜索条件
        $name = trim($this->input->get('name'));
        if($name){
            $this->tpl->assign("name", $name);
            $where .= " AND a.name = '$name' ";
        }
        //批次
        $pici = trim($this->input->get('pici'));
        if($pici){
            $this->tpl->assign("pici", $pici);
            $where .= " AND a.groupid = '$pici' ";
        }
        //状态
        $search_status = $this->input->get('search_status');
        if($search_status){
            $this->tpl->assign("search_status", $search_status);
            $where .= " AND a.status = $search_status ";
        }
        //工厂
        $factory_id = $this->input->get('search_factory');
        if($factory_id){
            $this->tpl->assign("search_factory", $factory_id);
            $where .= " AND a.fid = '$factory_id' ";
        }
        if($_COOKIE["classid"]==12)
        {
            if($_COOKIE['department']==5){ //工厂财务都可以看到 方便标完成

            }else{
                $where.=" AND a.fid =1";
            }

        }
        if($_COOKIE["classid"]==13)
        {
            if($_COOKIE['department']==5){ //工厂财务都可以看到 方便标完成

            }else{
                $where.=" AND a.fid =2";
            }

        }

        //供应商
        $supplier_id = $this->input->get('search_supplier');
        if($factory_id){
            $this->tpl->assign("search_supplier", $supplier_id);
            $where .= " AND a.supplierid = '$supplier_id' ";
        }
        $where .= " GROUP BY a.id ";
        $join = " LEFT JOIN d_factorysupplier b ON a.supplierid = b.id LEFT JOIN db_factory c ON a.fid = c.id LEFT JOIN d_user f ON f.id = a.operid ";
        $orderby = " order by a.id DESC";
        $fields = " a.id,a.name,a.quantity,a.price,a.unit,a.supplierid,a.status,a.groupid,a.fid, ".
            " a.remark,a.operid,a.opertime,b.name as supplier_name,c.name as factory_name,f.name as user_name ";
        $list = $this->fun->getalllist('d_factoryrawpur a', $where, $nowpage, $if_csv, $this->pageSize, $orderby,$fields,$join);
        //echo $this->db->last_query();exit;
        $pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
        $this->tpl->assign("orderlist", $list["list"]);
        $this ->tpl->display("factory/applybuylist.tpl");
    }
    //查看财务打款信息
    public function applyRemitList() {
        //拼接搜索条件
        $nowpage = $_REQUEST["pageid"];
        if ($nowpage == "") $nowpage = 1;
        $where = "";
        //商品编号，创建人，序号
        $name = trim($this->input->get('name'));
        if($name){
            $this->tpl->assign("name", $name);
            $where .= " AND a.name like '%$name%' ";
        }
        if($_COOKIE["classid"]==12)
        {
            if($_COOKIE['department']==5){ //工厂财务都可以看到 

            }else{
                $where.=" AND a.fid =1";
            }

        }
        if($_COOKIE["classid"]==13)
        {
            if($_COOKIE['department']==5){ //工厂财务都可以看到

            }else{
                $where.=" AND a.fid =2";
            }

        }


        $where .= " GROUP BY a.id ";
        $join = " LEFT JOIN db_factory c ON a.fid = c.id ";
        $orderby = " order by a.id DESC";
        $fields = " a.id,a.name,a.status,a.allprice,a.trueprice,a.fid,c.name as factory_name ";
        $list = $this->fun->getalllist('d_factoryrawpurgroup a', $where, $nowpage, $if_csv, $this->pageSize, $orderby,$fields,$join);
        //echo $this->db->last_query();exit;
        $pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
        $this->tpl->assign("orderlist", $list["list"]);
        $this ->tpl->display("factory/applyremitlist.tpl");
    }
    //删除打款信息
    public function delRemitInfo(){
        $id = $this->input->post('id');
        $this->db->from('d_factoryrawpurgroup');
        $this->db->where('id',$id);
        $result = $this->db->get()->row_array();
        if($result){
            $this->db->where('id',$id);
            $this->db->delete('d_factoryrawpurgroup');
            if($this->db->affected_rows()){
                $arr = array('code'=>1,'msg'=>'参数错误');
                echo json_encode($arr);exit;
            }else{
                $arr = array('code'=>0,'msg'=>'删除失败');
                echo json_encode($arr);exit;
            }
        }else{
            $arr = array('code'=>0,'msg'=>'参数错误');
            echo json_encode($arr);exit;
        }
    }
    //更新打款状态信息
    public function updRemitStatus(){
        $id = $this->input->post('id');
        $this->db->from('d_factoryrawpurgroup');
        $this->db->where('id',$id);
        $result = $this->db->get()->row_array();
        if($result){
            //默认为1 未打款状态
            $data['status']= 2;
            $this->db->where('id',$id);
            $this->db->update('d_factoryrawpurgroup',$data);
            if($this->db->affected_rows()){
                $arr = array('code'=>1,'msg'=>'打款成功');
                echo json_encode($arr);exit;
            }else{
                $arr = array('code'=>0,'msg'=>'打款失败');
                echo json_encode($arr);exit;
            }

        }else{
            $arr = array('code'=>0,'msg'=>'参数错误');
            echo json_encode($arr);exit;
        }
    }
    //单个申请打款，不是批量
    public function applyRemit(){
        $id = $this->input->post('id');
        $this->db->from('d_factoryrawpur');
        $this->db->where('id',$id);
        $result = $this->db->get()->row_array();
        if($result){
            //对另外一张财务表进行插入操作用于记录打款情况
            $data_finance['name'] = date("YmdHis");
            $data_finance['status'] = $result['status'];
            $data_finance['allprice'] = $result['price']*$result['quantity'];
            //$data_finance['trueprice'] = $result['price']*$result['quantity'];
            $data_finance['fid'] = $result['fid'];
            $data_finance['factoryrawpurids'] = $result['id'];
            $this->db->insert('d_factoryrawpurgroup',$data_finance);
            //获取插入的id，然后反插入主表
            $insert_id = $this->db->insert_id();
            //2为申请打款状态
            $data['status']= 2;
            $data['groupid']=$insert_id;
            $this->db->where('id',$id);
            $this->db->update('d_factoryrawpur',$data);


            if($this->db->affected_rows()){
                $arr = array('code'=>1,'msg'=>'申请成功');
                echo json_encode($arr);exit;
            }else{
                $arr = array('code'=>0,'msg'=>'申请失败');
                echo json_encode($arr);exit;
            }

        }else{
            $arr = array('code'=>0,'msg'=>'参数错误');
            echo json_encode($arr);exit;
        }
    }
    //订单作废
    public function cancelOrder(){
        $id = $this->input->post('id');
        $this->db->from('d_factoryrawpur');
        $this->db->where('id',$id);
        $result = $this->db->get()->row_array();
        if($result){
            //4为订单作废状态
            $data['status']= 4;
            $this->db->where('id',$id);
            $this->db->update('d_factoryrawpur',$data);
            if($this->db->affected_rows()){
                $arr = array('code'=>1,'msg'=>'作废成功');
                echo json_encode($arr);exit;
            }else{
                $arr = array('code'=>0,'msg'=>'作废失败');
                echo json_encode($arr);exit;
            }

        }else{
            $arr = array('code'=>0,'msg'=>'参数错误');
            echo json_encode($arr);exit;
        }
    }
    /*********正向开发商品报表*************/
    public function newproduct()
    {
        ini_set('max_execution_time', '0');
        $nowpage = $_REQUEST["pageid"];
        if ($nowpage == "")
            $nowpage = 1;
        $where = " AND a.status = 6 ";

        if($_COOKIE["department"] ==1  || $_COOKIE["classid"] ==11)
        {
            //管理员和财务进来能看到所有人的
            $developer= trim(urldecode($this->input->get_post('developer')));
            if($developer)
            {
                $where.=" AND a.versiondivision ='".$developer."'";
                $this->tpl->assign("developer", $developer);
            }
        }else{
            //其他人只能看到自己
          //  $where.=" AND a.versiondivision ='".$_COOKIE["username"]."'";

				if($_COOKIE["classid"] ==12)	//工厂1人员
				{
					$where.=" AND a.supplier = 1";	
				}
				
				if($_COOKIE["classid"] ==13)	//工厂2人员
				{
					$where.=" AND a.supplier = 2";	
				}
				if($_COOKIE["classid"] ==16)	//工厂3人员
				{
					$where.=" AND a.supplier = 7";	
				}

        }
	


        $other = trim($this->input->get_post('other'));
        if($other)
        {
            $where.=" AND a.sku like '%".$other."%'";
            $this->tpl->assign("other", $other);
        }
        $starttime=trim($this->input->get_post('starttime'));
        if($starttime)
        {
            $where.=" AND startdate >='".$starttime."'";
            $this->tpl->assign("starttime", $starttime);
        }
        $endtime= trim($this->input->get_post('endtime'));
        if($starttime)
        {
            $where.=" AND startdate <='".$endtime."'";
            $this->tpl->assign("endtime", $endtime);
        }
		
        $jiesuan = trim($this->input->get_post("jiesuan"));
        if($jiesuan){
            if($jiesuan==1){
                $where .= " AND a.versionUser_flag = 1 "; //已结算
            }
            if($jiesuan==2){
                $where .= " AND a.versionUser_flag = 0 "; //未结算
            }
            $this->tpl->assign("jiesuan",$jiesuan);
        }else{
            $where .= " AND a.versionUser_flag = 0 "; //未结算
        }
        $where.= " AND a.startdate IS NOT NULL ";
        $sql_totalmoney = "SELECT SUM(cutoff_money) as total_money FROM db_product_develop a WHERE 1 ".$where;
        $rs_totalmoney  = $this->db->query($sql_totalmoney)->row_array();
        $this->tpl->assign("total_money",$rs_totalmoney['total_money']);

        $orderby = " order by a.id DESC ";

        $fields = "a.id,a.sku,a.name,a.startdate,a.enddate,a.nums_30day,a.nums_90day,a.createName,a.cutoff_time,a.cutoff_money,b.name as versionUser ";
        $join = " LEFT JOIN d_user b ON a.versiondivision = b.id ";


        //显示数据
        $list = $this->fun->getalllist('db_product_develop a',$where,$nowpage,$if_csv,$this->pageSize,$orderby,$fields,$join);
        //echo $this->db->last_query();exit;
        $pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
        $this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
        $this->tpl->assign("list",$list["list"]);


        //打版师
        $sql = "SELECT DISTINCT(a.versiondivision) as id,b.name FROM db_product_develop a LEFT JOIN d_user b ON a.versiondivision = b.id WHERE versiondivision != 0 ";
        $userlist = $this->db->query($sql)->result_array();
        $this->tpl->assign("userlist", $userlist);
        $this ->tpl->display("factory/newproduct.tpl");
    }


    //新品开发结算报表
    public function newproductList()
    {
        $sku = trim($this->input->get('sku'));
        $sql_develop = "SELECT * FROM db_product_develop WHERE sku = '{$sku}' ";
        $rs_develop  = $this->db->query($sql_develop)->row_array();
        $where = " WHERE 1 ";
        $where.= " AND b.dates>= '{$rs_develop['startdate']}' AND b.dates <= '{$rs_develop['enddate']}' ";
        if($_COOKIE["department"] ==1  || $_COOKIE["classid"] ==11)
        {
            //管理员和财务进来能看到所有人的

        }else{
            //其他人只能看到自己
            //$where=" AND A.protector ='".$_COOKIE["username"]."'";
        }
        $where .= " AND a.goods_id in (SELECT goods_id FROM db_goods WHERE goods_parent_sku = '{$sku}') ";
        $where .= " AND b.order_status in(4,5) AND b.order_source in('正常订单','手工创建','拆分订单','合并订单') ";
        $where .= " GROUP BY a.order_id ";
        $fields = "a.order_id,b.order_sn,b.order_source,b.goods_amount,b.shipping_fee,b.pay_fee,b.platform_fee,b.shopname,b.shipping_realfee,b.shipping_expectfee,b.shipping_time";
        $sql = "SELECT {$fields} FROM db_order_sell a LEFT JOIN db_order_list b ON a.order_id = b.order_id ".$where;
        $rs  = $this->db->query($sql)->result_array();
        $total_money = 0;
        $total_costprice = 0;
        $total_profit = 0;
        foreach($rs as $k=>$v){
            $sql_costprice = "SELECT SUM(costprice) as costprice FROM db_order_sell WHERE order_id = '{$v['order_id']}' ";
            $rs_costprice  = $this->db->query($sql_costprice)->row_array();
            $rs[$k]['costprice'] = $rs_costprice['costprice'];
            $rs[$k]['profit'] = $v['goods_amount']+$v['shipping_fee']-$rs_costprice['costprice']-$v['platform_fee']-$v['pay_fee']-$v['shipping_realfee'];
            $total_money+=$v['goods_amount'];
            $total_costprice+=$rs_costprice['costprice'];
            $total_profit+=$rs[$k]['profit'];
            if($v['shipping_time']){
                $rs[$k]['shipping_time'] = date("Y-m-d H:i:s",$v['shipping_time']);
            }else{
                $rs[$k]['shipping_time'] = "";
            }

        }
        $this->tpl->assign("total_money",$total_money);
        $this->tpl->assign("total_costprice",$total_costprice);
        $this->tpl->assign("total_profit",$total_profit);
        $this->tpl->assign("list",$rs);
        $this -> tpl -> display("factory/newproductlist.tpl");
    }
    function ajaxbutton(){
        $op = $this->input->get_post('op');
        if($op =='findRemitDetails')
        {
            $id = $this->input->get('id');
            $sql = "SELECT * FROM d_factoryrawpurgroup WHERE id = $id ";
            $arr_row = $this->db->query($sql)->row_array();
            $arr_factoryrawpurs = explode(',',$arr_row['factoryrawpurids']);
            //显示查询结果数据
            $arr_info = array();
            foreach($arr_factoryrawpurs as $k=>$v){
                $fields = " a.id,a.name,a.quantity,a.price,a.unit,a.supplierid,a.status,a.groupid,a.fid, ".
                    " a.remark,a.operid,a.opertime,b.name as supplier_name,c.name as factory_name,f.name as user_name ";
                $this->db->from('d_factoryrawpur a');
                $this->db->select($fields);
                $this->db->where('a.id',$v);
                $this->db->join('d_factorysupplier b','a.supplierid = b.id','left');
                $this->db->join('db_factory c','a.fid = c.id','left');
                $this->db->join('d_user f','a.operid = f.id','left');
                $res = $this->db->get()->row_array();
                $arr_info[$k] = $res;
            }
            $this->tpl->assign("orderlist", $arr_info);
            $this ->tpl->display("factory/applyremitdetails.tpl");
        }
        //打版师 提成核算
        if($op =='savenewProductDate')
        {
            $kaideveloper = $this->input->post('kaideveloper');
            $cutofftime	  = $this->input->post('cutofftime');
            //保存结算人员和时间，需要保存已结算的订单信息
            $postdb="";
            $where = " AND status = 6 ";
            if($kaideveloper)
            {
                $where.=" AND versiondivision ='".$kaideveloper."'";
            }
            $sql = "SELECT * FROM db_product_develop WHERE 1 ".$where;
            $list=$this->db->query($sql)->result_array();
            foreach($list as $key=>$rs)
            {
                if($rs['versionUser_flag']){
                    continue;
                }
                if($rs['enddate']<$cutofftime){
                    //判断之前是否有记录已结算的值
                    $postdb["versionUser_flag"] = 1;
                    $this->db->update("db_product_develop",$postdb," id = '".$rs['id']."'");
                }

            }
            $this->fun->phpalert(2, "结算数据保存成功！","/applybuy/newproduct?developer={$kaideveloper}");
            exit;
        }
        if($op == 'applyBuyPrint'){
            $str_param = trim($this->input->get('param'),",");
            $arr_order_id = explode(",",$str_param); //order_id数组
            $arr_print = array(); //需要打印出来的数据
            foreach($arr_order_id as $k=>$v){
                //$v 为获取到的选中的id号 订单号
                $fields = " a.id,a.name,a.quantity,a.price,a.unit,a.supplierid,a.status,a.groupid,a.fid, ".
                    " a.remark,a.operid,a.opertime,b.name as supplier_name,c.name as factory_name,f.name as user_name ";
                $this->db->from('d_factoryrawpur a');
                $this->db->select($fields);
                $this->db->where('a.id',$v);
                $this->db->join('d_factorysupplier b','a.supplierid = b.id','left');
                $this->db->join('db_factory c','a.fid = c.id','left');
                $this->db->join('d_user f','a.operid = f.id','left');
                $res = $this->db->get()->row_array();
                $arr_info[$k] = $res;
            }
            $this->tpl->assign("orderlist", $arr_info);
            $this->tpl->display('factory/applybuydetailslist.tpl');
        }
        if($op=="updRemitStatus"){
            $id = $this->input->post('id');
            $money = $this->input->post('money');
            $this->db->from('d_factoryrawpurgroup');
            $this->db->where('id',$id);
            $result = $this->db->get()->row_array();
            if($result){
                //默认为1 未打款状态
                $data['status']= 2;
                $data['trueprice'] = $money;
                $this->db->where('id',$id);
                $this->db->update('d_factoryrawpurgroup',$data);
                //更新打款状态
                $this->db->update('d_factoryrawpur',array('status'=>3)," id in (".$result['factoryrawpurids'].")");

                if($this->db->affected_rows()){
                    $arr = array('code'=>1,'msg'=>'打款成功');
                    echo json_encode($arr);exit;
                }else{
                    $arr = array('code'=>0,'msg'=>'打款失败');
                    echo json_encode($arr);exit;
                }

            }else{
                $arr = array('code'=>0,'msg'=>'参数错误');
                echo json_encode($arr);exit;
            }
        }



    }





    //查看打款明细
    public function findRemitDetails(){
        $id = $this->input->get('id');
        $sql = "SELECT * FROM d_factoryrawpurgroup WHERE id = $id ";
        $arr_row = $this->db->query($sql)->row_array();
        $arr_factoryrawpurs = explode(',',$arr_row['factoryrawpurids']);
        //显示查询结果数据
        $arr_info = array();
        foreach($arr_factoryrawpurs as $k=>$v){
            $fields = " a.id,a.name,a.quantity,a.price,a.unit,a.supplierid,a.status,a.groupid,a.fid, ".
                " a.remark,a.operid,a.opertime,b.name as supplier_name,c.name as factory_name,f.name as user_name ";
            $this->db->from('d_factoryrawpur a');
            $this->db->select($fields);
            $this->db->where('a.id',$v);
            $this->db->join('d_factorysupplier b','a.supplierid = b.id','left');
            $this->db->join('db_factory c','a.fid = c.id','left');
            $this->db->join('d_user f','a.operid = f.id','left');
            $res = $this->db->get()->row_array();
            $arr_info[$k] = $res;
        }
        $this->tpl->assign("orderlist", $arr_info);
        $this ->tpl->display("factory/applyremitdetails.tpl");

    }

    //采购申请表打印
    public function applyBuyPrint(){
        $str_param = trim($this->input->get('param'),",");
        $arr_order_id = explode(",",$str_param); //order_id数组
        $arr_print = array(); //需要打印出来的数据
        foreach($arr_order_id as $k=>$v){
            //$v 为获取到的选中的id号 订单号
            $fields = " a.id,a.name,a.quantity,a.price,a.unit,a.supplierid,a.status,a.groupid,a.fid, ".
                " a.remark,a.operid,a.opertime,b.name as supplier_name,c.name as factory_name,f.name as user_name ";
            $this->db->from('d_factoryrawpur a');
            $this->db->select($fields);
            $this->db->where('a.id',$v);
            $this->db->join('d_factorysupplier b','a.supplierid = b.id','left');
            $this->db->join('db_factory c','a.fid = c.id','left');
            $this->db->join('d_user f','a.operid = f.id','left');
            $res = $this->db->get()->row_array();
            $arr_info[$k] = $res;
        }
        $this->tpl->assign("orderlist", $arr_info);
        $this->tpl->display('factory/applybuydetailslist.tpl');
    }
    //申请批量打款,需要对批量打款的id进行验证，已付款的不能再进行计算
    public function applyBatchRemit(){
        $str_param = trim($this->input->get_post('param'),",");
        $arr_order_id = explode(",",$str_param); //order_id数组
        $this->db->trans_begin();
        $str_id = "";
        $totalprice = 0;
        try{
            foreach($arr_order_id as $k=>$v){
                $data['status'] = 2; //该状态为申请打款状态
                $s = "SELECT * FROM d_factoryrawpur WHERE id = $v AND status = 1 ";
                $res = $this->db->query($s)->row_array();
                if($res){
                    $this->db->where('id',$v);
                    $this->db->update('d_factoryrawpur',$data);
                    $str_id.= $v.",";
                    //价格计算
                    $totalprice += $res['price']*$res['quantity'];

                }
            }
            $str_id = trim($str_id,",");
            $sql = "SELECT sum(price) as price,sum(quantity) as quantity,fid FROM d_factoryrawpur WHERE id in ($str_id) ";
            $result = $this->db->query($sql)->row_array();
            //对另外一张财务表进行插入操作用于记录打款情况
            $data_finance['name'] = date("YmdHis");
            $data_finance['status'] = 1;
            $data_finance['allprice'] = $totalprice;
            //$data_finance['trueprice'] = $totalprice;
            $data_finance['fid'] = $result['fid'];
            $data_finance['factoryrawpurids'] = $str_id;

            $this->db->insert('d_factoryrawpurgroup',$data_finance);
            $insert_id = $this->db->insert_id();//获取批次号并插入相关批次号
            $order_arr = explode(",",$str_id);
            foreach($order_arr as $k=>$v){
                    $this->db->where('id',$v);
                    $order_data['groupid']=$insert_id;
                    $this->db->update('d_factoryrawpur',$order_data);
            }
            $this->db->trans_commit();
            $arr = array('code'=>1,'msg'=>'申请成功');
            echo json_encode($arr);exit;

        }catch(Exception $e)
        {
            $this->db->trans_rollback();
            $arr = array('code'=>0,'msg'=>'申请失败');
            echo json_encode($arr);exit;
        }

        //$url = base_url('/applybuy/applyRemitList');
        //redirect($url);
    }
    public function addApplyBuy(){
        if($this->input->post()){
            $arr_post = $this->input->post();
            //var_dump($arr_post['name']);exit;
            //查询当前用户所在的工厂
            $userid = $_COOKIE['userid'];
            $sql = "SELECT * FROM d_user WHERE id = $userid ";
            $rs = $this->db->query($sql)->row_array();
            $fid = $rs['classid'];
            $date = date("Y-m-d H:i:s");
            foreach($arr_post['name'] as $k=>$v){
                //赋值并对数据库进行操作
                 if($v&&$arr_post['quantity'][$k]){
                     $arr['name'] = $arr_post['name'][$k];
                     $arr['price'] = $arr_post['price'][$k];
                     $arr['quantity'] = $arr_post['quantity'][$k];
                     $arr['status'] = 1; //为新创建订单
                     $arr['unit'] = $arr_post['unit'][$k];
                     $arr['supplierid'] = $arr_post['search_factory'][$k]; //注意该项为供应商id
                     $arr['remark'] = $arr_post['groupid'][$k]; //注意该项为备注
                     $arr['operid'] = $_COOKIE['userid'];
                     $arr['opertime'] = $date;
                     if($fid==12){
                         $arr['fid'] = 1;
                     }
                     if($fid==13){
                         $arr['fid'] = 2;
                     }


                     $this->db->insert('d_factoryrawpur',$arr);
                 }
            }
            $url = base_url('applybuy/applyList');
            redirect($url);

        }else{
            //获取所有供应商列表
            $suppliers = $this->fun->getdatabaseslist("d_factorysupplier");
            $this->tpl->assign("suppliers",$suppliers);
            $this->tpl->display('factory/applybuyadd.tpl');
        }
    }
    //新创建的订单编辑窗口
    public function edit(){
        if($this->input->post()){
            $data['name'] = $this->input->post('name');
            $data['price'] = $this->input->post('price');
            $data['quantity'] = $this->input->post('quantity');
            $data['unit'] = $this->input->post('unit');
            $data['supplierid'] = $this->input->post('search_factory');
            $data['remark'] = $this->input->post('groupid');
            $id = $this->input->post('showid');
            $this->db->where('id',$id);
            $this->db->update('d_factoryrawpur',$data);
            $url = base_url('applybuy/applyList');
            redirect($url);
        }else{
            $id = $this->input->get('id');
            //获取所有供应商列表
            $suppliers = $this->fun->getdatabaseslist("d_factorysupplier");
            $this->tpl->assign("suppliers",$suppliers);
            $sql = "SELECT * FROM d_factoryrawpur WHERE id = $id ";
            $result = $this->db->query($sql)->row_array();
            $this->tpl->assign("factoryrawpur",$result);
            $this->tpl->display('factory/applybuyedit.tpl');

        }







    }

}